<template>
  <t-modal
    :title="title"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
    v-bind:confirmLoading="confirmLoading"
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <div class="sub-title">基本信息</div>
        <a-form-model-item label="上级任务" prop="labelInValue">
          <a-tree-select
            :disabled="isDisabled"
            v-model="form.labelInValue"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="superiorSource"
            :replaceFields="{
              children: 'childList',
              title: 'name',
              key: 'uuid',
              value: 'uuid',
            }"
            placeholder="请选择"
            :load-data="onLoadData"
            labelInValue
          >
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="任务名称" prop="name">
          <a-input
            v-model="form.name"
            placeholder="请输入"
            :disabled="isDisabled"
          >
          </a-input>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="节点等级" prop="nodeLevel">
              <a-select
                style="width: 100%"
                placeholder="青选择"
                v-model="form.nodeLevel"
                :disabled="isDisabled"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in nodeLevelSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="节点类型" prop="nodeType">
              <a-select
                style="width: 100%"
                placeholder="青选择"
                v-model="form.nodeType"
                :disabled="isDisabled"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in nodeTypeSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="计划开始时间" prop="planStartTime">
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.planStartTime"
                :disabled-date="disabledStartDate"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                @change="startDateChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="计划结束时间" prop="planEndTime">
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.planEndTime"
                :disabled-date="disabledEndDate"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                @change="endDateDateChange"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="周期(天)" prop="duration">
              <a-input v-model="form.duration" disabled> </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="关键节点" prop="major">
              <a-radio-group v-model="form.major" :disabled="isDisabled">
                <a-radio :value="1"> 是 </a-radio>
                <a-radio :value="2"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>

        <div class="sub-title">
          前置任务
          <a-button type="primary" @click="handelAddEvent()" v-if="!isDisabled">
            新增
          </a-button>
        </div>
        <vxe-table
          ref="xTable"
          border="inner"
          align="center"
          max-height="400"
          :data="tableData"
          :column-config="{ resizable: true }"
          :scroll-y="{ enabled: true }"
          :scroll-x="{ enabled: true }"
          :edit-rules="validRules"
          :loading="loading"
          :row-config="{ keyField: 'uuid' }"
          :edit-config="{ showAsterisk: true }"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="labelInValue" title="任务名称" min-width="200">
            <template slot-scope="scope">
              <a-tree-select
                :disabled="isDisabled"
                v-model="scope.row.labelInValue"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="taskSource"
                :replaceFields="{
                  children: 'childList',
                  title: 'name',
                  key: 'uuid',
                  value: 'taskId',
                }"
                placeholder="请选择"
                :load-data="onLoadData"
                @change="changeTaskEvent($event, scope)"
                labelInValue
              >
              </a-tree-select>
            </template>
          </vxe-column>
          <vxe-column field="type" title="类型">
            <template slot-scope="scope">
              <a-select
                v-model="scope.row.type"
                style="width: 100%"
                :disabled="isDisabled"
                placeholder="请选择"
                @change="$refs.xTable.updateStatus(scope)"
              >
                <a-select-option value="FS">
                  完成-开始
                </a-select-option>
                <a-select-option value="SS">
                  开始-开始
                </a-select-option>
                <a-select-option value="FF">
                  完成-完成
                </a-select-option>
                <a-select-option value="SF">
                  开始-完成
                </a-select-option>
              </a-select>
            </template>
          </vxe-column>
          <vxe-column field="duration" title="间隔时间(天)">
            <template slot-scope="scope">
              <a-input-number
                v-model="scope.row.duration"
                :min="0"
                :disabled="isDisabled"
                placeholder="请输入"
                @change="$refs.xTable.updateStatus(scope)"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="status"
            title="状态"
            width="100"
            v-if="operateType == 2"
          >
            <template slot-scope="scope">
              <span :class="[filterStatusClass(scope.row.status)]">{{
                filterStatusName(scope.row.status)
              }}</span>
            </template>
          </vxe-column>
          <vxe-column
            title="操作"
            fixed="right"
            align="center"
            width="100"
            v-if="!isDisabled"
          >
            <template slot-scope="scope">
              <div class="text-button-group">
                <a-button
                  type="link"
                  class="danger"
                  @click="handleDeleteEvent(scope.row, scope.rowIndex)"
                >
                  删除
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </a-form-model>
    </div>
  </t-modal>
</template>

<script>
import cloneDeep from "lodash.clonedeep";
import moment from "moment";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
import { getDicItemByCode } from "@/api/common.js";
import {
  getConfigDetail,
  getConfigDetailDraft,
  getConfigDetailHistory,
  savePlanData,
  getTreeListDraft,
  getTreeListDraftChildren,
} from "@/api/progressManage";
export default {
  inject: ["versionSource", "conditionsSource", "moduleSource"],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      title: "编辑",
      isDisabled: false,
      confirmLoading: false,
      footer: {},
      form: {
        //上级任务
        labelInValue: undefined,
        //任务名称
        name: "",
        //周期
        duration: "",
        //节点等级
        nodeLevel: undefined,
        //节点类型
        nodeType: undefined,
        //计划开始时间
        planStartTime: "",
        //计划结束时间
        planEndTime: "",
        //关键节点
        major: "",
      },
      rules: {
        labelInValue: [
          {
            required: true,
            message: "请选择上级任务",
          },
        ],

        name: [
          {
            required: true,
            message: "请输入任务名称",
          },
        ],

        nodeLevel: [
          {
            required: true,
            message: "请输入节点等级",
          },
        ],
        nodeType: [
          {
            required: true,
            message: "请选择节点类型",
          },
        ],

        planStartTime: [
          {
            required: true,
            message: "请选择计划开始时间",
          },
        ],
        planEndTime: [
          {
            required: true,
            message: "请选择计划结束时间",
          },
        ],
        major: [
          {
            required: true,
            message: "请选择是否关键节点",
          },
        ],
      },
      loading: false,
      tableData: [],
      validRules: {
        labelInValue: [
          {
            required: true,
            message: "请选择",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择",
          },
        ],
        duration: [
          {
            required: true,
            message: "请输入",
          },
        ],
      },
      //上级任务
      superiorSource: [],
      //任务名称
      taskSource: [],
      //节点类型
      nodeTypeSource: [],
      //节点等级
      nodeLevelSource: [],
      //
      cloneTreeData: [],
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          Promise.all([
            this.filterTitle(),
            this.getProjectType(),
            this.getProjectLevel(),
            this.getTaskData(),
          ]);
          if (this.operateType != 3) {
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    //查询节点类型
    getProjectType() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "scheduleType" })
          .then((res) => {
            let { data } = res;
            this.nodeTypeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.nodeTypeSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询节点等级
    getProjectLevel() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "nodeLevel" })
          .then((res) => {
            let { data } = res;
            this.nodeLevelSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.nodeLevelSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询任务名称
    getTaskData() {
      let { proCode, orgCode = "" } = this.parameter;
      let { uuid } = this.versionSource();
      let { tenantCode } = this.conditionsSource();
      return new Promise((resolve, reject) => {
        getTreeListDraft({
          proCode: proCode ? proCode : tenantCode,
          versionId: uuid,
          orgCode,
          nodeType: this.moduleSource(),
        })
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            let cloneTreeData = cloneDeep(filterData);
            this.superiorSource = filterData;
            this.taskSource = cloneTreeData;
            this.recursiveTree(this.taskSource);
            resolve();
          })
          .catch((_) => {
            this.taskSource = [];
            reject();
          });
      });
    },

    onLoadData(treeNode) {
      return new Promise((resolve) => {
        const { uuid, childList } = treeNode.dataRef;
        if (!childList || (childList && childList.length == 0)) {
          let { proCode, orgCode = "" } = this.parameter;
          let { tenantCode } = this.conditionsSource();
          getTreeListDraftChildren({
            parentId: uuid,
            proCode: proCode ? proCode : tenantCode,
            orgCode,
            versionId: this.versionSource().uuid,
          })
            .then((res) => {
              let source = res?.data || [];
              source.forEach((v) => {
                let { isLast } = v;
                v.isLeaf = isLast;
              });
              let filterData = addAttributeByKey(
                null,
                "scopedSlots",
                { icon: "custom" },
                source,
                "childList"
              );
              let cloneTreeData = cloneDeep(filterData);
              treeNode.dataRef.childList = cloneTreeData;
              this.superiorSource = [...this.superiorSource];
              this.taskSource = [...this.taskSource];
              this.recursiveTree(this.taskSource);
              setTimeout((_) => {
                resolve();
              }, 200);
            })
            .catch((_) => {});
        } else {
          resolve();
        }
      });
    },

    //处理任务树
    recursiveTree(data = []) {
      data.forEach((item) => {
        this.$set(item, "disabled", !item.lastFlag);
        if (item.childList && item.childList.length > 0) {
          this.recursiveTree(item.childList);
        }
      });
    },

    handelAddEvent() {
      this.tableData.push({
        sourceTaskId: undefined,
        sourceTaskName: "",
        labelInValue: undefined,
        type: undefined,
        duration: "",
        status: "",
      });
    },

    handleDeleteEvent(row, index) {
      this.tableData.splice(index, 1);
    },

    changeTaskEvent(event, scope) {
      let { label, value } = event;
      let { rowIndex } = scope;
      this.tableData[rowIndex].sourceTaskId = value;
      this.tableData[rowIndex].sourceTaskName = label;
      //   this.$refs.xTable.updateStatus(scope);
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form, tableData, versionSource } = this;
          let { uuid = "", proCode } = this.parameter;
          let { tenantCode } = this.conditionsSource();

          let formJson = {
            uuid,
            orgCode: "",
            versionId: versionSource().uuid,
            parentId: form.labelInValue.value,
            proCode: proCode ? proCode : tenantCode,
            //任务名称
            name: form.name,
            //节点等级
            nodeLevel: form.nodeLevel,
            //节点类型
            nodeType: form.nodeType,
            //周期
            duration: form.duration,
            //计划开始时间
            planStartTime: form.planStartTime,
            //计划结束时间
            planEndTime: form.planEndTime,
            //关键节点
            major: form.major,
            //前置任务
            predecessorList: tableData,
          };
          const $table = this.$refs.xTable;
          const errMap = await $table.validate(true).catch((errMap) => errMap);
          if (errMap) {
            return;
          }
          this.confirmLoading = true;
          savePlanData(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.closeModal();
                this.$parent.getData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "操作失败");
            })
            .finally((_) => {
              this.confirmLoading = false;
            });
        }
      });
    },

    getConfigDetail,
    getConfigDetailDraft,
    getConfigDetailHistory,
    //详情
    getDetail() {
      return new Promise((resolve, reject) => {
        let { status = "" } = this.versionSource();
        let { uuid, proCode } = this.parameter;
        let apiUrl = "";
        if (status == 4) {
          //正式
          apiUrl = "getConfigDetail";
        } else if (status == 5) {
          //历史
          apiUrl = "getConfigDetailHistory";
        } else {
          //草稿
          apiUrl = "getConfigDetailDraft";
        }
        this[apiUrl]({
          uuid,
          proCode,
        })
          .then((res) => {
            this.form = {
              //上级任务
              labelInValue: {
                label: res.data.parentName,
                value: res.data.parentId,
              },
              //任务名称
              name: res.data?.name,
              //节点等级
              nodeLevel: res.data?.nodeLevel,
              //节点类型
              nodeType: res.data?.nodeType,
              //周期
              duration: res.data?.duration,
              //计划开始时间
              planStartTime: res.data?.planStartTime,
              //计划结束时间
              planEndTime: res.data?.planEndTime,
              //关键节点
              major: res.data?.major,
            };
            let source = res.data?.predecessorList ?? [];
            source.forEach((v) => {
              this.$set(v, "labelInValue", {
                label: v.sourceTaskName,
                value: v.sourceTaskId,
              });
            });
            this.tableData = source;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            reject();
          });
      });
    },
    //重置表单
    resetForm() {
      this.tableData = [];
      this.form = {
        //上级任务
        labelInValue: undefined,
        //任务名称
        name: "",
        //周期
        duration: "",
        //节点等级
        nodeLevel: undefined,
        //节点类型
        nodeType: undefined,
        //计划开始时间
        planStartTime: "",
        //计划结束时间
        planEndTime: "",
        //关键节点
        major: "",
      };
      this.$refs.ruleForm.resetFields();
    },
    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //开始时间
    startDateChange() {
      let { form } = this;
      let dyas = this.getDaysBetween(form.planStartTime, form.planEndTime);
      if (dyas) form.duration = dyas;
    },
    //结束时间
    endDateDateChange() {
      let { form } = this;
      let dyas = this.getDaysBetween(form.planStartTime, form.planEndTime);
      if (dyas) form.duration = dyas;
    },

    disabledStartDate(current) {
      let startTime = moment(this.form.planEndTime).valueOf();
      let currentTime = current.valueOf();
      return currentTime > startTime;
    },
    disabledEndDate(current) {
      let endTime = moment(this.form.planStartTime).valueOf();
      let currentTime = current.valueOf();
      return currentTime < endTime;
    },
    getDaysBetween(startDate, enDate) {
      const sDate = Date.parse(startDate);
      const eDate = Date.parse(enDate);
      if (sDate > eDate) {
        return 0;
      }
      if (sDate == eDate) {
        return 1;
      }
      const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
      return days + 1;
    },
    //标题
    filterTitle() {
      let { operateType } = this;
      switch (operateType) {
        //
        case 1:
          this.title = "编辑";
          this.isDisabled = false;
          this.footer = {};
          break;
        //
        case 2:
          this.title = "查看";
          this.isDisabled = true;
          this.footer = { footer: null };
          break;
        //
        case 3:
          this.title = "新增";
          this.isDisabled = false;
          this.footer = {};
          break;
        default:
          break;
      }
    },
    filterStatusClass(val) {
      switch (Number(val)) {
        case 1:
          return "default";
        case 2:
          return "warning";
        case 3:
          return "success";
        default:
          return "default";
      }
    },

    filterStatusName(val) {
      switch (Number(val)) {
        case 1:
          return "未开始";
        case 2:
          return "进行中";
        case 3:
          return "已完成";
        default:
          return "未开始";
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 120px;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }

    .sub-title {
      padding-left: 30px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #525a5d;
      position: relative;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &::after {
        content: "";
        width: 3px;
        height: 16px;
        background: #1890ff;
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
      }
      .ant-btn {
        margin-right: 0;
      }
    }
    .default {
      color: #8c8c8c;
    }
    .success {
      color: #4bc964;
    }
    .warning {
      color: #f07f17;
    }
  }
}
</style>
